/** 
 * Copyright (c) luogu-admin-group 2023-2023. All rights resvered.
 */

/* eslint-disable @typescript-eslint/restrict-template-expressions */

import { sleep, initArticle, getClzHTML, lgContent, MaxCount as MAXCOUNT, reasons as REASONS, colorStyle, getAcceptArticles, jsxToDom, HistoryCom, IHistory } from './utils'
import { renderHeader } from './header'
import { divideArticles } from './divideArticles'
import { getCssStyle } from './cssStyle';
import { Table as ATable, Card, Modal } from '@arco-design/web-react';
import { addTopBar } from './topbar';
import React from "react";
import { ColumnProps } from '@arco-design/web-react/es/Table';
/**
 * 
 * @param {"accept" | "decline"} operation 操作类型，可选 `accept` 或 `decline`
 * @param {string} reason 拒绝原因，当 `operation` 为 `accept` 时无效
 * @param {number} id 博客 id
 * @returns {void}
 */
export function sendResult(operation: "accept" | "decline" = "accept", reason: string = "", id: number): void {
    let nedid = 0;
    for (; nedid < window.Arc.length; nedid++) {
        if (window.Arc[nedid].getAttribute(`data-blogid`) == window.articleList[id].blogid.toString()) {
            break;
        }
    }
    if (operation !== "accept" && (window.Show[nedid] as HTMLInputElement).checked === true) {
        reason += (/[;；]$/.test(reason) ? "" : "；") + `审核管理员：${window.USERNAME}，对审核结果有疑问请私信交流。`;
    }
    const payload = { reason, operation };
    // 更新剩余题解数
    const asfd = document.getElementsByClassName("am-u-sm-12 solution-content")[0];
    const remain = Number((asfd.firstElementChild!.lastElementChild as HTMLElement).innerText) - 1;
    if (remain > 0)
        asfd.firstElementChild!.innerHTML = (asfd.firstElementChild!.innerHTML.toString()).split(`当`)[0] + ` 当前共有 <b id = "lastCountNum">${remain}</b> 篇题解博客待审核。 当前页面全部审核完毕后，会自动刷新加载新的一页。`;
    else {
        asfd.firstElementChild!.innerHTML = (asfd.firstElementChild!.innerHTML.toString()).split(`当`)[0] + `已经审核完了呢。`
    }
    // 提交审核结果
    $.post(`/webadmin/blog/reviewSolution/${window.articleList[id].blogid}`, payload, (_resp) => {
        if (_resp !== 200) console.log(payload, _resp);
    });
    if (nedid >= window.Arc.length) {
        try {
            throw Error(`unfind artical with blog-id ${window.articleList[id].blogid}`)
        }
        catch (e) {
            console.error(e);
        }
        return;
    }
    window.Arc[nedid].parentNode!.parentNode!.removeChild(window.Arc[nedid].parentNode!);
    window.nowCount--;
    if (window.nowCount !== 0) {
        // here is not Arc.length - 1 because we have remove one Element from Arc before; 
        if (nedid !== window.Arc.length) {
            window.Arc[nedid].parentElement!.scrollIntoView()
        } else {
            (window.Arc[nedid - 1].parentElement as Element).scrollIntoView()
        }
    }


    if (operation === "accept") {
        window.articleList[id].passed = true;
        window.adminHistory.accept++;
    }
    else {
        window.articleList[id].passed = false;
        window.adminHistory.decline++;
    }

    (document.getElementById("accept_rate") as Element).innerHTML =
        `您的通过率：${window.adminHistory.accept}/${window.adminHistory.accept + window.adminHistory.decline}=${(window.adminHistory.accept / (window.adminHistory.accept + window.adminHistory.decline)).toFixed(2)}%`;
    window.articleList[id].time = (new Date()).getTime();
    window.adminHistory.articles.push(window.articleList[id]);
    localStorage.setItem('adminHistory', JSON.stringify(window.adminHistory));

    if (window.nowCount === 0) {
        setTimeout(() => {
            location.reload();
        }, 1100);
    }
    findNowView();
}



/**
 * 初始化 LocalStorage
 * @param usernmae 用户名
 * @returns {void}
 */
function initLocalStorage(usernmae: string): void {
    localStorage.setItem('USERNAME', usernmae)
    localStorage.setItem('reasons', JSON.stringify(REASONS))
    localStorage.setItem('MaxCount', JSON.stringify(MAXCOUNT))
    if (localStorage.getItem('usingKill') === null) localStorage.setItem('usingKill', '1')
    if (localStorage.getItem('usingadminHistory') === null) localStorage.setItem('usingadminHistory', '1')
    if (localStorage.getItem('usingShow') === null) localStorage.setItem('usingShow', '1')
    if (localStorage.getItem('usingClz') === null) localStorage.setItem('usingClz', '1')
    if (localStorage.getItem('usingUnfold') === null) localStorage.setItem('usingUnfold', '1')
    if (localStorage.getItem('adminHistory') === null) {
        const adminHistory: IHistory = { articles: [], accept: 0, decline: 0 }
        localStorage.setItem('adminHistory', JSON.stringify(adminHistory));
    }
    localStorage.setItem('colorStyle', JSON.stringify(colorStyle))
    if (localStorage.getItem('usingRate') === null) localStorage.setItem('usingRate', '1')

}


/**
 * 
 * @param id 文章在该界面的**原始**位置
 */
export function KILL(id: number) {/*id->Original i,i->Present i*/
    // 原因
    let rea = "";
    // 选择原因
    for (let j = id * window.ri.length; j < (id + 1) * window.ri.length; j++) {
        // 选择了该理由
        if ((document.getElementById(`show${j.toString()}`) as HTMLElement).style.display !== "none") {
            // 默认字段
            rea += window.reasons.normalReasons[window.ri[j % window.ri.length]].list[window.RI[j % window.RI.length]].full;
            // 手写补充字段
            if ((document.getElementById("input" + j) as HTMLInputElement).value !== "") {
                rea += "（" + (document.getElementById("input" + j) as HTMLInputElement).value + "）";
            }
            if (window.ReasonPositions[j].size > 0) {
                rea += `（位置：`
                for (let now of window.ReasonPositions[j]) {
                    rea += `\`${now}\`、`

                }
                rea = rea.substring(0, rea.length - 1);
                rea += `）`
            }
            rea += "；";
        }
    }
    // 其他原因
    if ((document.getElementById("other" + id) as HTMLInputElement).value !== "") {
        rea += (document.getElementById("other" + id) as HTMLInputElement).value;
    }
    sendResult("decline", rea, id);
}
/**
 * 开启题解审核优化
 */
export async function Enhance_Kill() {
    window.ReasonPositions = [];
    let cnt = -1;
    for (let j = 0; j < window.Arc.length; j++) {
        let tmp = document.createElement("div");
        let rtmp = document.createElement("div");
        for (let i = 0; i < 16; i++)tmp.append(window.Arc[j].lastElementChild as Element);
        for (let i = 0; i < 16; i++)rtmp.append(tmp.lastElementChild as Element);
        window.ORI.append(rtmp);
    }//删除原先内容
    for (let j = 0; j < window.Arc.length; j++) {
        let tot = -1;
        let options =
            <div className='exadmin-reasons-container'>
                <div>
                    <div className="exadmin_reason_toolbar">
                        <b>题解审核选项</b>
                        <span>
                            <svg className='icon' style={{ width: "1.35em", height: "1.35em", verticalAlign: "middle", fill: "currentColor", overflow: "hidden" }} viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="1640">
                                <path d="M880.288 232.48L560.192 45.12a95.648 95.648 0 0 0-96.64 0L143.68 232.48A96.64 96.64 0 0 0 96 315.904v397.664c0 34.784 18.624 66.88 48.736 84l320 181.92a95.52 95.52 0 0 0 94.496 0l320-181.92A96.576 96.576 0 0 0 928 713.568V315.904a96.64 96.64 0 0 0-47.712-83.424zM864 713.568c0 11.584-6.208 22.304-16.256 28l-320 181.92a31.776 31.776 0 0 1-31.488 0l-320-181.92A32.192 32.192 0 0 1 160 713.568V315.904c0-11.456 6.048-22.048 15.904-27.808l319.872-187.36a31.84 31.84 0 0 1 32.192 0l320.128 187.392c9.856 5.728 15.904 16.32 15.904 27.776v397.664zM512 320a192 192 0 1 0 0 384 192 192 0 0 0 0-384z m0 320a128 128 0 1 1 0-256 128 128 0 0 1 0 256z" p-id="1641">

                                </path>
                            </svg>
                            <input type="checkbox" className="SHOW" checked={(window.usingShow) ? true : false} />
                            显示审核员信息
                        </span>
                        <span className='close-solution' title='关闭本题题解'>
                            <svg aria-hidden="true" focusable="false" data-prefix="fas" data-icon="lock" role="img" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 448 512" className="svg-inline--fa fa-lock fa-w-14" style={{ height: "1em", display: "inline-block", paddingLeft: "5px", paddingTop: "3px", color: "orangered" }}>
                                <path data-v-a97ae32a="" fill="currentColor" d="M400 224h-24v-72C376 68.2 307.8 0 224 0S72 68.2 72 152v72H48c-26.5 0-48 21.5-48 48v192c0 26.5 21.5 48 48 48h352c26.5 0 48-21.5 48-48V272c0-26.5-21.5-48-48-48zm-104 0H152v-72c0-39.7 32.3-72 72-72s72 32.3 72 72v72z">
                                </path>
                            </svg>
                        </span>
                        <b id={`Warning${j}`} style={{ color: "red" }}></b>

                    </div>
                </div>
                <div className="exadmin-fatal-reasons">
                    <button ref={(target) => { target?.style.setProperty('background-color', 'rgb(34,177,76)', 'important'); }} className="exadmin-btn exadmin-btn-accept" title="通过题解！" id={`acceptButton${j}`} style={{ marginRight: "2em", backgroundColor: "rgb(1,1,1)" }} onClick={(event) => {
                        sendResult('accept', '', Number(((event.target as Element).id as string).substring(12)));
                    }}>
                        通过
                    </button>

                    <button className='exadmin-btn exadmin-btn-reject' title='与题解区解法大量重复' id={`rejectButton1${j}`} style={{ marginRight: ".5em" }} onClick={(event) => {
                        sendResult('decline', '与题解区解法大量重复', Number(((event.target as Element).id as string).substring(13)));
                    }}>
                        拒绝：解法重复
                    </button>
                    <button className='exadmin-btn exadmin-btn-reject' title='文章内容与他人文章大量雷同，涉嫌抄袭' id={`rejectButton2${j}`} style={{ marginRight: ".5em" }} onClick={(event) => {
                        sendResult('decline', '文章内容与他人文章大量雷同，涉嫌抄袭', Number(((event.target as Element).id as string).substring(13)));
                    }}>
                        拒绝：文章雷同
                    </button><button className='exadmin-btn exadmin-btn-reject' title='文章含有违规内容' id={`rejectButton3${j}`} style={{ marginRight: ".5em" }} onClick={(event) => {
                        sendResult('decline', '文章含有违规内容', Number(((event.target as Element).id as string).substring(13)));
                    }}>
                        拒绝：违规内容
                    </button>
                </div>
                <div className='exadmin-other-reasons'>
                    <div className='other-reason-container'>
                        <input className='exadmin-other-reason-input' style={{ width: "100%" }} id={`other${j.toString()}`} placeholder="其他理由（请在每条理由末尾加上分号）" />
                        {

                            window.reasons.normalReasons.map((reasonType) => {
                                return <>
                                    {
                                        reasonType.list.map((reason) => {
                                            window.ReasonPositions.push(new Set<string>())
                                            ++cnt;
                                            ++tot;
                                            return <div className='exadmin-reason-each-input-container' style={{ width: "100%", display: "none" }} id={`show${cnt}`}>
                                                <span className="exadmin-reason-text" title={`${reason.full}`} style={{ marginRight: "8px" }}>
                                                    {reason.display}
                                                </span>
                                                <span>
                                                    <input className="exadmin-reason-each-input" placeholder="详细理由（请在每条理由末尾加上分号）" style={{ marginLeft: "2em", width: "75%", fontSize: "14px" }} id={`input${cnt}`} />
                                                </span>
                                                <span>
                                                    <button id={`positionButton${cnt}`} onClick={(e) => {
                                                        const Cid = +((e.target as HTMLElement).id.split(`Button`)[1])
                                                        document.getElementById(`Content${Cid}`)!.innerText = window.articleList[Math.floor((Cid - 1) / window.ri.length)].blogContent;
                                                        document.getElementById(`position${Cid}`)!.style.display = "block"
                                                    }}>
                                                        位置批注
                                                    </button>
                                                    <div id={`position${cnt}`} style={{ background: "var(--color-bg-2)", position: "fixed", width: "75%", height: "80vh", top: `12vh`, left: `10vw`, zIndex: 2, display: "none" }} >
                                                        <Card
                                                            title={`位置批注：${reason.display}`}
                                                            extra={
                                                                <button id={`positionFinishButton${cnt}`} onClick={(e) => { document.getElementById(`position${(e.target as HTMLElement).id.split(`Button`)[1]}`)!.style.display = "none" }}>完成</button>
                                                            }
                                                            style={{ overflow: "auto", width: "50vw", height: "100%" }}>
                                                            <div style={{ overflow: "auto", width: "100%", height: "100%" }}>
                                                                <span id={`Content${cnt}`} style={{ width: "100%", height: "100%", overflow: "auto" }}
                                                                    onMouseUp={(e) => {
                                                                        let s = window.getSelection()?.toString()
                                                                        if ((!s) || (s === "")) { return }
                                                                        let selectionId = (e.target as HTMLElement).id.split(`Content`)[1]
                                                                        Modal.confirm({
                                                                            title: '确认选择',
                                                                            content: <>
                                                                                {`请确认选择的位置：`}
                                                                                <pre style={{ overflow: "auto", maxHeight: "350px", width: "400px" }}>
                                                                                    <code style={{ width: "365px", display: "block" }}>
                                                                                        {s}
                                                                                    </code>
                                                                                </pre>
                                                                            </>
                                                                            ,
                                                                            onOk: async () => {
                                                                                window.ReasonPositions[+(selectionId)].add(s!);
                                                                                document.getElementById(`positionSelected${+(selectionId)}`)?.appendChild(await jsxToDom(
                                                                                    <div style={{ width: "20vw", height: "5vh", marginTop: "8px" }}>
                                                                                        <div style={{ float: "left", height: "5vh", maxWidth: "16vw", overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap", backgroundColor: "#F2F2F2", border: "thick double #32a1ce" }}>
                                                                                            {s}
                                                                                        </div>
                                                                                        <svg xmlns="http://www.w3.org/2000/svg" version="1.1" width="15" height="15"
                                                                                            style={{ cursor: "pointer", marginTop: "8px", marginLeft: "8px" }}
                                                                                            onClick={(e) => {
                                                                                                let nowId = 0, fa;
                                                                                                if ((e.target as HTMLElement).tagName === `line`) {
                                                                                                    fa = (e.target as HTMLElement).parentElement!.parentElement!.parentElement!.parentElement!
                                                                                                    nowId = +(fa.id.split(`positionSelected`)[1]);
                                                                                                    fa.removeChild((e.target as HTMLElement).parentElement!.parentElement!.parentElement!)
                                                                                                    window.ReasonPositions[nowId].delete(((e.target as HTMLElement).parentElement!.parentElement!.firstElementChild as HTMLElement).innerText!);

                                                                                                }
                                                                                                else {
                                                                                                    fa = (e.target as HTMLElement).parentElement!.parentElement!.parentElement!
                                                                                                    nowId = +(fa.id.split(`positionSelected`)[1]);
                                                                                                    fa.removeChild((e.target as HTMLElement).parentElement!.parentElement!)
                                                                                                    window.ReasonPositions[nowId].delete(((e.target as HTMLElement).parentElement!.firstElementChild as HTMLElement).innerText!);

                                                                                                }

                                                                                                // window.ReasonPositions[nowId].delete(((e.target as HTMLElement).parentElement!.firstElementChild as HTMLElement).innerText!);
                                                                                                let listTry = []
                                                                                                for (let now of window.ReasonPositions[nowId].values()) {
                                                                                                    listTry.push(now)
                                                                                                }
                                                                                            }}>
                                                                                            <line
                                                                                                x1="0"
                                                                                                y1="0"
                                                                                                x2="15"
                                                                                                y2="15"
                                                                                                stroke="steelblue"
                                                                                                stroke-width="2"
                                                                                            />
                                                                                            <line
                                                                                                x1="15"
                                                                                                y1="0"
                                                                                                x2="0"
                                                                                                y2="15"
                                                                                                stroke="steelblue"
                                                                                                stroke-width="2"
                                                                                            />
                                                                                        </svg>
                                                                                    </div>
                                                                                ))
                                                                            }
                                                                        })
                                                                    }}
                                                                >
                                                                </span>
                                                            </div>
                                                        </Card>
                                                        <div style={{ position: "fixed", top: "12vh", left: "60vw", width: "25vw", height: "80vh", padding: "2rem" }}>
                                                            <p style={{ color: "red" }}>
                                                                使用鼠标选中对应文字即可，如未弹出提示框请单击选中的文字，建议位置批注尽量短小。
                                                            </p>
                                                            <p> 已选择的位置：</p>
                                                            <div id={`positionSelected${cnt}`} style={{ width: "23vw", height: "50vh", overflow: "auto" }}>

                                                            </div>
                                                        </div>
                                                    </div>
                                                </span>

                                            </div >
                                        })
                                    }
                                </>

                            })
                        }
                    </div>
                    <div className='exadmin-big-reject'>
                        <button ref={(target) => {
                            target?.style.setProperty("background-color", "rgb(255, 64, 129)", "important");
                        }} id={`killButton${j}`} className='exadmin-btn exadmin-btn-reject' style={{ marginTop: "1em" }} onClick={(event) => {
                            KILL(Number(((event.target as Element).id as string).substring(10)));
                        }}>
                            毙掉题解
                        </button>
                    </div>
                    {
                        (() => { cnt -= tot + 1; return <></> })()
                    }
                    {

                        window.reasons.normalReasons.map((reasonType) => {
                            return <>
                                <div className='exadmin-reason-list'>
                                    <div className='exadmin-reasons-toolbar' onClick={(event) => {
                                        $((event.target as HTMLElement).parentElement!).toggleClass('onshow');
                                    }}>
                                        {reasonType.title}
                                        <a style={{ float: "right" }}>
                                            <svg className="icon" style={{ width: "2em", height: "1.5em", verticalAlign: "middle", fill: "#ddd", overflow: "hidden" }} viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="754">
                                                <path d="M533.333333 605.866667L341.333333 413.866667l29.866667-29.866667 162.133333 162.133333L695.466667 384l29.866666 29.866667-192 192z" fill="#444444" p-id="755">
                                                </path>
                                            </svg>
                                        </a>
                                    </div>
                                    <div className='exadmin-reasons'>
                                        {
                                            reasonType.list.map((reason) => {
                                                ++cnt;
                                                ++tot;
                                                return <span className='exadmin-reason-text' title={reason.full} id={`choice${cnt}`} style={{ marginRight: "8px" }} onClick={(event) => {
                                                    const ElementId = ((event.target as Element).id as string).substring(6);
                                                    if ((document.getElementById(`show${ElementId}`) as HTMLElement).style.display === 'none') {
                                                        $(event.target as HTMLElement).toggleClass('picked');
                                                        (document.getElementById(`show${ElementId}`) as HTMLElement).style.display = `block`;
                                                    }
                                                    else {
                                                        $(event.target as HTMLElement).toggleClass('picked');
                                                        (document.getElementById(`show${ElementId}`) as HTMLElement).style.display = `none`;

                                                    }
                                                }}>
                                                    {reason.display}
                                                </span>
                                            })
                                        }
                                    </div>
                                </div>

                            </>

                        })

                    }
                </div >

            </div >

        window.Arc[j].append(await jsxToDom(options));

        // 悬停展开
        if (window.usingUnfold === 1) {
            const targetElements = document.getElementsByClassName("exadmin-reason-list");
            for (let i = 0; i < targetElements.length; i++) {
                const $div = $(targetElements[i]);
                $div.on({
                    mouseenter: () => $div.addClass('onshow'),
                    mouseleave: () => $div.removeClass('onshow'),
                });
            }
        }
    }
}
export async function showhistory() {

    for (let j = 0; j < window.Arc.length; j++) {
        (window.Arc[j].parentElement as HTMLElement).style.display = "none";
    }
    document.getElementById(`clzDiv`)?.setAttribute(`style`, "display:none");
    (document.getElementsByClassName(`admin-sidebar am-offcanvas`)[0] as HTMLElement).style.width = '150px'
    const pageselector = document.getElementsByClassName("am-g");
    (pageselector[0] as HTMLElement).style.display = "none";
    const b = document.getElementsByClassName("admin-content-body");
    let z = document.getElementsByClassName(`am-cf am-padding`)[0];
    if (z) {
        z.remove();
    }
    let historyDiv = <div id='history-field' className='am-cf am-padding' style={{ display: 'block', marginTop: "30px" }}>
        <ATable columns={HistoryCom as unknown as ColumnProps<IArticleWithoutContent>[]} data={window.adminHistory.articles} pagePosition="bottomCenter" pagination={{ pageSize: 10 }} column-resizable size="middle">

        </ATable>
    </div>
    b[0].appendChild(await jsxToDom(historyDiv));
    b[0].scrollIntoView()
}
/**
 * 检查现在审核的是哪篇题解，用于粉兔模式
 */
async function findNowView() {
    let art_elements = document.getElementsByClassName(`am-article`)
    let pos: Array<number> = [];
    for (let i = 0; i < art_elements.length; i++) {
        let now = art_elements[i];
        pos.push(now.getBoundingClientRect().bottom);
    }
    const now = pos.findIndex(dy =>
        dy > 50
    );
    if (!window.nowPreview || now != window.nowPreview) {
        window.nowPreview = now;
        if (window.nowPreview >= 0 && window.nowPreview < window.articleList.length && window.articleList[window.nowPreview].HTMLNoKaTeX === ``) {
            getClzHTML(window.articleList[window.nowPreview]);
        }
    }
}

async function clz_start(blogid: number) {//陈亮舟，启动！
    let j = 0, k = 0;
    const ArticleDivHTML = document.getElementsByClassName("am-article");
    for (; k < ArticleDivHTML.length; k++) {
        if (ArticleDivHTML[k].getAttribute(`data-blogid`) === blogid.toString()) {
            break;
        }
    }
    for (; j < window.articleList.length; j++)if (window.articleList[j].blogid === blogid) break;
    if (window.articleList[j].HTMLNoKaTeX === '') {
        await getClzHTML(window.articleList[j]);
    }
    if (window.articleList[j].clzMode === false) {
        window.articleList[j].ORIHTML = (ArticleDivHTML[k].querySelector(`.am-article-bd`) as Element).innerHTML;
        (ArticleDivHTML[k].querySelector(`.am-article-bd`) as Element).innerHTML = window.articleList[j].HTMLNoKaTeX;
    } else (ArticleDivHTML[k].querySelector(`.am-article-bd`) as Element).innerHTML = window.articleList[j].ORIHTML;
    window.articleList[j].clzMode = !window.articleList[j].clzMode;
}

async function main(): Promise<void> {
    // 非审核界面
    if (!location.href.startsWith('https://www.luogu.com.cn/webadmin/blog/review')) return;
    // 分割文章
    divideArticles()
    const articleDoms: NodeListOf<HTMLElement> = document.querySelectorAll('article')
    // 这一页题解的数量
    let articleCnt = articleDoms.length;
    window.articleList = [];
    const data = await lgContent('/problem/P1001')
    window.ORI = document.createElement("div");

    initLocalStorage(data.currentUser.name);
    const MaxCount = JSON.parse(localStorage.getItem('MaxCount')!);
    window.adminHistory = JSON.parse(localStorage.getItem('adminHistory')!);
    window.reasons = JSON.parse(localStorage.getItem('reasons')!);
    window.USERNAME = localStorage.getItem('USERNAME')!
    window.usingRate = Number(localStorage.getItem('usingRate'));
    window.usingKill = Number(localStorage.getItem('usingKill')!);
    window.usingShow = Number(localStorage.getItem('usingShow'));
    window.usingAdminHistory = Number(localStorage.getItem('usingadminHistory')!);
    window.usingUnfold = Number(localStorage.getItem('usingUnfold')!)
    window.Arc = document.getElementsByClassName("am-article");
    GM_addStyle(getCssStyle())
    if (window.usingAdminHistory === 1) {
        let t = document.createElement("li");
        let historyButton = document.createElement(`a`);
        historyButton.id = `history-button`;
        historyButton.addEventListener(`click`, () => {
            showhistory();
        })
        historyButton.innerHTML = `<span class="am-icon-history"></span> 历史记录`;
        t.appendChild(historyButton);
        (document.getElementById("discuss-collapse-nav") as Element).append(t);
    }

    if (window.usingKill === 1) {
        Enhance_Kill();
    }
    const clzToggleDiv = <div id="clzDiv" style={{ position: 'fixed', right: '30px', bottom: '50px', width: "50px" }} onClick={() => {
        let artDivs = document.getElementsByClassName(`am-article`);
        clz_start(Number(artDivs[window.nowPreview].getAttribute(`data-blogid`)))
    }}>
        <svg className="icon" width={`80%`} style={
            {
                width: '80%',
                height: '80%',
                verticalAlign: 'middle',
                fill: 'currentColor',
                overflow: 'hidden'
            }} viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="1428">
            <path d="M942.2 486.2C847.4 286.5 704.1 186 512 186c-192.2 0-335.4 100.5-430.2 300.3-7.7 16.2-7.7 35.2 0 51.5C176.6 737.5 319.9 838 512 838c192.2 0 335.4-100.5 430.2-300.3 7.7-16.2 7.7-35 0-51.5zM512 766c-161.3 0-279.4-81.8-362.7-254C232.6 339.8 350.7 258 512 258c161.3 0 279.4 81.8 362.7 254C791.5 684.2 673.4 766 512 766zM508 336c-97.2 0-176 78.8-176 176s78.8 176 176 176 176-78.8 176-176-78.8-176-176-176z m0 288c-61.9 0-112-50.1-112-112s50.1-112 112-112 112 50.1 112 112-50.1 112-112 112z" p-id="1429">
            </path>
        </svg>
    </div>
    addTopBar();
    document.getElementsByClassName(`am-cf admin-main`)[0].appendChild((await jsxToDom(clzToggleDiv)));

    for (let nowShowId = 0; nowShowId < articleCnt; ++nowShowId) {
        let p = await initArticle(articleDoms[nowShowId])
        window.articleList.push(p);
        let warnCloseSolution = document.getElementById(`Warning${nowShowId}`)!
        warnCloseSolution.innerHTML = `${+window.articleList[nowShowId].present >= MaxCount[+window.articleList[nowShowId].color] ? (`本题题解数量超过 ${MaxCount[+window.articleList[nowShowId].color]} 篇，请及时上报`) : ""}`
        let newKillButton = document.getElementById(`killButton${nowShowId}`)!
        newKillButton.setAttribute(`pid`, `${window.articleList[nowShowId].pid}`);
    }

    const $header: JQuery<HTMLElement> = $(document.head)
    $header.before('<link rel="stylesheet" href="https://cdn.luogu.com.cn/css/amazeui.min.css">')

    window.Show = document.getElementsByClassName("SHOW");
    window.ri = [];
    window.RI = [];
    window.oid = [];
    for (let j = 0; j < window.Arc.length; j++)window.oid.push(j);
    for (let i = 0; i < window.reasons.normalReasons.length; i++) {
        for (let k = 0; k < window.reasons.normalReasons[i].list.length; k++) {
            window.ri.push(i); window.RI.push(k);
        }
    }

    const RATE = document.getElementsByClassName("am-g");
    ((RATE[0].firstElementChild as Element).firstElementChild as Element).innerHTML =
        `<div class="div-mate" id="accept_rate" style="display:none;">您的通过率：${window.adminHistory.accept + window.adminHistory.decline > 0 ? window.adminHistory.accept + '/' + (window.adminHistory.accept + window.adminHistory.decline) + '=' + (window.adminHistory.accept / (window.adminHistory.accept + window.adminHistory.decline) * 100).toFixed(2) + '%' : '您尚无题解审核记录'}</div>` + ((RATE[0].firstElementChild as Element).firstElementChild as Element).innerHTML;

    if (window.usingRate === 1) {
        (document.getElementById(`accept_rate`) as Element).setAttribute(`style`, ``);
    }

    if (window.usingShow === 0) for (let i = 0; i < window.Show.length; i++) {
        (window.Show[i] as HTMLInputElement).checked = false;
    }

    (document.querySelector(`.admin-content`) as HTMLElement).onscroll = findNowView;


    for (let e of window.articleList) {
        if (e.HTMLNoKaTeX === ``) {
            await getClzHTML(e);
        }
    }
    await sleep(1000);
    for (let p of window.articleList) {
        await renderHeader(p);
    }

    getAcceptArticles(window.articleList);

}
export { main }